package com.myutils;

import android.app.Application;
import android.widget.Toast;

import com.nativec.tools.ModuleManager;
import com.nativec.tools.SerialPort;
import com.nativec.tools.SerialPortFinder;
import com.reader.helper.ReaderHelper;
import com.uhf.uhf.R;

import java.io.File;
import java.io.IOException;
import java.security.InvalidParameterException;

/**
 * 类描述：UHF连接工具类<br/>
 * 创建人：lwj<br/>
 * 创建时间：2019/8/13 11:27 <br/>
 */
public class UHFConnectUtils {
    public static SerialPort mSerialPort = null;
    /**
     * 波特率
     */
    private int baud = 115200;
    private ReaderHelper mReaderHelper;

    private UHFConnectUtils() {
    }

    public static UHFConnectUtils newInstance() {
        return new UHFConnectUtils();
    }

    /**
     * 关闭连接
     */
    public static void close() {
        if (mSerialPort != null) {
            mSerialPort.close();
        }
    }

    public void onCreate(Application application) {
        SerialPortFinder serialPortFinder = new SerialPortFinder();
//        String[] allDevices = serialPortFinder.getAllDevices();
//        String[] allDevicesPath = serialPortFinder.getAllDevicesPath();
        try {
            mSerialPort = new SerialPort(new File("/dev/ttyS4"), baud, 0);
            //mSerialPort = new SerialPort(new File("/dev/ttymxc2"), baud, 0); //天线设备串口
            mReaderHelper = ReaderHelper.getDefaultHelper();
            mReaderHelper.setReader(mSerialPort.getInputStream(), mSerialPort.getOutputStream());
            if (!ModuleManager.newInstance().setUHFStatus(true)) {
                throw new RuntimeException("UHF RFID power on failure,may you open in other" +
                        " Process and do not exit it");
            }
        } catch (SecurityException e) {
            Toast.makeText(
                    application.getApplicationContext(),
                    application.getApplicationContext().getResources().getString(R.string.error_security),
                    Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            Toast.makeText(
                    application.getApplicationContext(),
                    application.getApplicationContext().getResources().getString(R.string.error_unknown),
                    Toast.LENGTH_SHORT).show();
        } catch (InvalidParameterException e) {
            Toast.makeText(
                    application.getApplicationContext(),
                    application.getApplicationContext().getResources().getString(R.string.error_configuration),
                    Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
